<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="stuObj.name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="stuObj.age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="stuObj.gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addOrUpdateUser()">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in stus" :key="item.id">
          <td>{{index + 1}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edit(item)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
  <script src="./vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        stuObj: {
          id: '',
          name: '',
          age: '',
          gender: ''
        },
        stus: []
      },
      methods: {
        addOrUpdateUser() {
          // console.log(this.stuObj)
          // 如果当前id存在于数组中，则是修改
          let flag = this.stus.some(item => item.id === this.stuObj.id)
          if (flag) {
            // 修改
            let index = this.stus.findIndex(item => item.id === this.stuObj.id)
            this.stus.splice(index, 1, this.stuObj)
          } else {
            // 新增
            if (!this.stuObj.name.trim()) return alert('请输入姓名！')
            if (!this.stuObj.age) return alert('请输入年龄！')
            if (this.stuObj.age <= 0) return alert('请检查年龄！')
            if (!this.stuObj.gender) return alert('请输入性别！')
            this.stuObj.id = Date.now()
            this.stus.push(this.stuObj)
          }
          this.stuObj = {
            id: '',
            name: '',
            age: '',
            gender: ''
          }
        },
        del(index) {
          this.stus.splice(index, 1)
        },
        edit(item) {
          this.stuObj = {
            id: item.id,
            name: item.name,
            age: item.age,
            gender: item.gender
          }
        }
      }
    })
  </script>
</body>

</html>